package com.bwie.lib_core.network;

import com.bwie.lib_core.filed.UrlFiled;
import com.bwie.lib_core.network.interceptor.SignInterceptor;
import com.bwie.lib_core.network.interceptor.TokenInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 单独Sign retrofit对象
 * */
public class SignInterfaceHttpRetrofitImpl implements HttpRetrofit{

    private static Retrofit retrofit = null;//建造后最终成果
    @Override
    public Retrofit getRetrofit() {
        return retrofit;
    }

    //针对接口请求的retrofit对象的建造者
    public static class SignInterfaceHttpRetrofitBuilder{
        private final long connectTime = 30;//连接超时30s
        private final long readTime = 30;//读取超时30s
        //建造外部类对象
        public SignInterfaceHttpRetrofitImpl build(){
            if (retrofit == null)
                createRetrofit();
            return new SignInterfaceHttpRetrofitImpl();
        }

        //创建过程隐藏->只对外提供retrofit对象供需要发起网络请求地点进行
        //网络请求->保护内部retrofit配置防止被用户修改
        //针对网络请求中的接口请求，具有短平快的特点
        private void createRetrofit(){
            //获取http网络请求地址以及返回值log打印
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//完整打印http请求
            //自定义sign拦截器
            SignInterceptor signInterceptor = new SignInterceptor();
            OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
            okHttpBuilder.connectTimeout(connectTime, TimeUnit.SECONDS);
            okHttpBuilder.readTimeout(readTime,TimeUnit.SECONDS);
            //添加必要拦截器
            okHttpBuilder.addInterceptor(loggingInterceptor);
            okHttpBuilder.addInterceptor(signInterceptor);
            OkHttpClient client = okHttpBuilder.build();
            //配置对应的retrofit对象
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.client(client);
            builder.baseUrl(UrlFiled.BASEURL);
            builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
            builder.addConverterFactory(GsonConverterFactory.create());
            retrofit = builder.build();
        }

    }

}
